<template>
    <div class="app-container">
        <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="资讯类型">
                        <el-select v-model="form.articleType" :style="{ width: '100%' }" placeholder="请选择类型"
                            @change="selectChange">
                            <el-option v-for="item in articleTypeList" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="标题图">
                        <el-upload class="avatar-uploader" :action="url" :show-file-list="false"
                            :on-success="uploadSuccess" :limit="1" :file-list="fileList" :headers="headers"
                            :before-upload="checkUpload" :disabled="flag">
                            <img v-if="files.path" :src="base_url + files.path" class="avatar" width="100px"
                                height="100px">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="排序" prop="sort">
                        <el-input v-model="form.sort" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序"
                            value="0" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                    <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">
                        {{ dict.dictLabel }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <vue-ueditor-wrap v-model="form.content" :config="myConfig"></vue-ueditor-wrap>
            </el-form-item>
            <el-form-item size="large">
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
    getArticleTypeList,
    addArticle,
    getArticle,
    updateArticle,
} from "@/api/zx/article";
import VueUeditorWrap from 'vue-ueditor-wrap';

export default {
    props: [],
    components: {
        VueUeditorWrap
    },
    data() {
        return {
            isXsYc: false,//是否显示移出
            articleTypeList: null,//类型
            base_url: process.env.VUE_APP_BASE_API,
            //文件列
            fileList: [],
            fileMediaList: [],
            fileListMore: [],
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            //上传地址
            url: process.env.VUE_APP_BASE_API + "/common/upload",
            //是否禁用上传
            flag: false,
            //图片路径
            files: { path: '' },
            // 表单校验
            dialogImageUrl: '',
            dialogVisible: false,
            myConfig: {
                // 编辑器不自动被内容撑高
                autoHeightEnabled: false,
                // 初始容器高度
                initialFrameHeight: 540,
                // 初始容器宽度
                initialFrameWidth: '100%',
                //启用自动保存
                enableAutoSave: true,
                // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！部署在国外的服务器，如果无法访问，请自备梯子）
                serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId=' + this.$store.getters.userInfo.userId,
                // serverUrl:'http://35.201.165.105:8000/controller.php',
                // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
                UEDITOR_HOME_URL: '/ueditor/',
                zIndex: 1
            },
            form: {
                id: undefined,
                name: undefined,
                content: undefined,
                logo: undefined,
                status: "1",
                createBy: undefined,
                createTime: undefined,
                sort: 0,
                contentType: undefined,
                pics: undefined,
                description: undefined,
                mediaFile: undefined,
                skipUrl: undefined,
                wxClientId: undefined,
                author: '',
            },
            rules: {
                name: [
                    { required: true, message: "名称不能为空", trigger: "blur" }
                ],
                articleType: [{
                    required: true,
                    message: '请选资讯类型',
                    trigger: 'blur'
                }],
                contentType: [{
                    required: true,
                    message: '请选择内容类型',
                    trigger: 'blur'
                }],
                releaseTime: [{
                    required: true,
                    message: '请选择发布日期',
                    trigger: 'blur'
                }],
                status: [
                    { required: true, message: '请选择状态', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ]
            },
            // 状态字典
            statusOptions: [],
            // 删除标志字典
            delFlagOptions: [],
            // 内容类型字典
            contentTypeOptions: [],
            picsAction: '/img',
            picsfileList: [],
            //赛事资讯类型
            dataTypeList: [
                { name: '焦点新闻', value: '1' },
                { name: "筹备动态", value: "2" },
            ]
        }
    },
    computed: {},
    watch: {},
    created() {
        this.mounted();
        this.getDicts("article_status").then(response => {
            this.statusOptions = response.data;
        });
        this.getDicts("article_del_flag").then(response => {
            this.delFlagOptions = response.data;
        });
        this.getDicts("article_content_type").then(response => {
            this.contentTypeOptions = response.data;
        });
    },
    methods: {
        mounted() {
            //类型字典
            getArticleTypeList().then(response => {
                this.articleTypeList = response.data;
            })
            this.form.id = this.$route.query.id;
            console.log(this.form.id)
            //根据id判断是否回显数据
            if (this.form.id != "" && this.form.id != undefined && this.form.id != null) {
                getArticle(this.$route.query.id).then(response => {
                    this.form = response.data;
                    if (response.data.mediaFile) {
                        this.fileMediaList = [{
                            url: this.base_url + response.data.mediaFile,
                            name: response.data.mediaFile,
                            fileName: response.data.mediaFile
                        }];
                    }
                    this.files.path = response.data.logo
                });
            }
        },
        // 状态字典翻译
        statusFormat(row, column) {
            return this.selectDictLabel(this.statusOptions, row.status);
        },
        // 删除标志字典翻译
        delFlagFormat(row, column) {
            return this.selectDictLabel(this.delFlagOptions, row.delFlag);
        },
        // 内容类型
        contentTypeFormat(row, column) {
            return this.selectDictLabel(this.contentTypeOptions, row.contentType);
        },
        submitForm() {
            console.log("form", this.form.releaseTime)

            this.$refs['elForm'].validate(valid => {
                if (!valid) return
                if (this.fileMediaList.length > 0) {
                    this.form.mediaFile = this.fileMediaList[0].fileName;
                    console.log("获取到媒体文件名称：" + this.fileMediaList[0].fileName)
                }

                if (this.form.id != undefined) {
                    updateArticle(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            var location = '/base/agreement/agreementManager';
                            this.$router.push({ 'path': location, 'query': {} })
                        }
                    });
                } else {
                    addArticle(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            var location = '/base/agreement/agreementManager';
                            this.$router.push({ 'path': location, 'query': {} })
                        }
                    });
                }
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields();
            this.fileList = [];
            fileMediaList: [];
        },
        picsBeforeUpload(file) {
            let isRightSize = file.size / 1024 / 1024 < 2
            if (!isRightSize) {
                this.$message.error('文件大小超过 2MB')
            }
            return isRightSize
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        /** 上传之前的校验 */
        checkUpload(file) {
            console.log("文件类型", file)
            const imgType = file.type
            //图片不大于2M
            const isLtSize = file.size / 1024 / 1024 < 2
            if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
                this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
                return false;
            }
            if (!isLtSize) {
                this.$message.error(`上传图片大小不能超过2MB!`)
                return false;
            }
        },
        checkUpload2(file) {
            console.log("文件类型", file)
            //视频不能大于100m
            const isLtSize = file.size / 1024 / 1024 < 100
            if (!isLtSize) {
                this.$message.error(`上传视频不能大于100m!`)
                this.isXsYc = true;
                return false;
            }
        },
        /** 上传成功后的回调 */
        uploadSuccess(response, file, fileList) {
            console.log("11112" + response.fileName);
            console.log(file);
            this.form.logo = response.fileName
            this.files.path = response.fileName
            this.flag = true
        },
        handleSuccess(file, fileMediaList) {
            console.log('上传成功', file, fileMediaList)
            if (typeof fileMediaList == "array") {
                fileMediaList.filter(e => {
                    e.url = e.response.url;
                    e.fileName = e.response.fileName;
                    this.form.mediaFile = e.response.url;
                })
                this.fileMediaList = fileMediaList;
            } else {
                fileMediaList.url = fileMediaList.response.url;
                fileMediaList.fileName = fileMediaList.response.fileName;
                this.fileMediaList = [fileMediaList];
                this.form.mediaFile = fileMediaList.response.url;
            }
        },
        handleExceed(e) {
            console.log(e)
            this.$message({
                message: '请先删除已有文件后，再进行上传',
                type: 'error'
            });
        },
        beforeRemove(file, fileMediaList) {
            if (this.isXsYc) {
                return;
            }
            console.log('移除', file, fileMediaList);
            this.$message({
                type: 'success',
                message: '移除成功!'
            });
            this.fileMediaList = [];
            return;
        },
        selectChange(id) {
            const types = this.articleTypeList.filter(item => item.id == id);
            if (types.length > 0) {
                this.form.wxClientId = types[0].wxClientId;
            }
        }
    }
}

</script>
<style scoped>
.el-upload__tip {
    line-height: 1.2;
}

.avatar-uploader i {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader i:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>